#include "BlockQueue.hpp"
#include "Task.hpp"
#include <time.h>
#include <unistd.h>
void *consumption(void *args)
{
    // 消费线程
    BlockQueue<Task<int>> *bq = static_cast<BlockQueue<Task<int>> *>(args);
    while (true)
    {
        usleep(1000);
        //消费
        Task<int> t = bq->pop();
        //计算
        t();
        std::cout << "消费了一个任务: "<<t.getresult()<<std::endl;
        sleep(1);

    }
}
void *produce(void *args)
{
    // 生产线程
    BlockQueue<Task<int>> *bq = static_cast<BlockQueue<Task<int>> *>(args);
    while (true)
    {
        // 获取任务
        char op=opers[rand()%opers.size()];
        Task<int> t(rand()%20,rand()%21,op);
        // int x=rand()%10+1;
        usleep(1000);
        bq->push(t);
        std::cout << "生产了一个任务: " <<t.gettask()<< std::endl;
        //sleep(1);
    }
}
void create_pthread(pthread_t *cid, pthread_t *pid, BlockQueue<Task<int>> *&bq)
{
    int ret1 = pthread_create(cid, NULL, consumption, bq);
    if (ret1 == 0)
        std::cout << "consumption create success" << std::endl;
    else
    {
        perror("consumption create fail");
        exit(1);
    }
    int ret2 = pthread_create(pid, NULL, produce, bq);
    if (ret2 == 0)
        std::cout << "produce create success" << std::endl;
    else
    {
        perror("produce create fail");
        exit(1);
    }
}

int main()
{
    srand(time(nullptr));
    // 创建队列
    pthread_t cid, pid;
    BlockQueue<Task<int>> *bq = new BlockQueue<Task<int>>(12);
    // 创建生产消费线程
    create_pthread(&cid, &pid, bq);
    // pthread_create(&cid,nullptr,consumption,bq);
    // pthread_create(&pid,nullptr,produce,bq);

    // 销毁线程
    pthread_join(cid, nullptr);
    pthread_join(pid, nullptr);
    // 释放队列内存
    delete bq;
    return 0;
}